package jenkins.plugins.publish_over_ssh.onepublish;

import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;

import java.io.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;


/**
 * 计算大文件MD5 
 *  David  2012-10-12
 */
public class Md5Util {
   
    static MessageDigest MD5 = null;


    static {
        try {
        MD5 = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException ne) {
        ne.printStackTrace();
        }
    }


    /**
     * 对一个文件获取md5值
     * @return md5串
     */
    public static String getMD5(File file) {
        FileInputStream fileInputStream = null;
        try {
        fileInputStream = new FileInputStream(file);
            byte[] buffer = new byte[8192];
            int length;
            while ((length = fileInputStream.read(buffer)) != -1) {
            MD5.update(buffer, 0, length);
            }


            return new String(Hex.encodeHex(MD5.digest()));
        } catch (FileNotFoundException e) {
        e.printStackTrace();
            return null;
        } catch (IOException e) {
        e.printStackTrace();
            return null;
        } finally {
            try {
                if (fileInputStream != null)
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 求一个字符串的md5值
     * @param target 字符串
     * @return md5 value
     */
    public static String MD5(String target) {
        return DigestUtils.md5Hex(target);
    }

    /**
     * linux环境获取本地文件MD5
     * @param localDir 字符串
     * @return map value
     */
    public static Map<String,String> getMd5Inlinux(String localDir){
        Map<String,String> localMd5=new HashMap<String,String>();
        String cmd="find "+localDir+"/ -type f -print0 | xargs -0  md5sum ";
        try {
            String[] cmdA = { "/bin/sh", "-c", cmd };
            Process process = Runtime.getRuntime().exec(cmdA);
            LineNumberReader br = new LineNumberReader(new InputStreamReader(
                    process.getInputStream()));
              /*StringBuffer sb = new StringBuffer();  */
            String line;
            while ((line = br.readLine()) != null) {
                  /*System.out.println(line);
                  sb.append(line).append("\n");*/
                localMd5.put(line.split("  ")[1], line.split("  ")[0]);
            }
            return localMd5;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}